package com.xuecheng.filesystem.service;

import com.alibaba.fastjson.JSON;
import com.xuecheng.filesystem.dao.FileSystemRepository;
import com.xuecheng.framework.domain.filesystem.FileSystem;
import com.xuecheng.framework.domain.filesystem.response.FileSystemCode;
import com.xuecheng.framework.domain.filesystem.response.UploadFileResult;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.utils.FileSizeConver;
import com.xuecheng.framework.utils.VerifyFileType;
import org.apache.commons.lang3.StringUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * FileSystemService
 */
@Service
public class FileSystemService {
    // FastDFS配置
    @Value("${xuecheng.fastdfs.tracker_server}")
    private String tracker_server;
    @Resource
    private FileSystemRepository fileSystemRepository;
    /**
     * 文件上传接口
     *
     * @param multipartFile 文件
     * @param businesskey   业务key
     * @param filetag       文件标签
     * @param metadata      元信息,Json字符,服务器会转换成Map对象
     * @return 上传后响应
     */
    public UploadFileResult upload(MultipartFile multipartFile, String businesskey, String filetag, String metadata) {
        if (multipartFile==null){
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_FILEISNULL);
        }
        if (multipartFile.getSize() > 1024*1024*30){
            // 图片不能超过30M
            ExceptionCast.cast(FileSystemCode.FS_THE_UPLOAD_FILE_CANNOT_EXCEED_30M);
        }
        // 将文件上传到fastDFS中,得到一个文件id
        String fileId = fast_upload(multipartFile);
        if (StringUtils.isEmpty(fileId)){
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_SERVERFAIL);
        }
        //将文件id和其他信息存入mongoDB中
        FileSystem fileSystem = new FileSystem();
        fileSystem.setFilePath(fileId);
        fileSystem.setFileId(fileId);
        fileSystem.setFiletag(filetag);
        fileSystem.setFileSizeByByte(multipartFile.getSize());
        fileSystem.setFileSizeByString(FileSizeConver.conver(multipartFile.getSize()));
        fileSystem.setBusinesskey(businesskey);
        fileSystem.setFileName(multipartFile.getOriginalFilename());
        fileSystem.setFileType(multipartFile.getContentType());

        // 判断是否需要存入原信息
        if (!StringUtils.isEmpty(metadata)){
            try {
                Map mate = JSON.parseObject(metadata, Map.class);
                LocalDateTime time=LocalDateTime.now();
                DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy年-MM月-dd日 HH时:mm分:ss秒");
                String strDate2 = dtf2.format(time);
                mate.put("上传时间", strDate2);
                fileSystem.setMetadata(mate);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            LocalDateTime time=LocalDateTime.now();
            DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String strDate2 = dtf2.format(time);
            Map map = new HashMap();
            map.put("上传时间", strDate2);
            fileSystem.setMetadata(map);
        }

        FileSystem save = fileSystemRepository.save(fileSystem);
        return new UploadFileResult(CommonCode.SUCCESS,save);
    }

    /**
     * fastdfs上传
     *
     * @param multipartFile 需要上传的文件
     * @return 存在fastdfs中的文件id
     */
    private String fast_upload(MultipartFile multipartFile) {
        // 初始化FastDFS环境
        initFastDFS();
        // 创建trackerClient
        TrackerClient trackerClient = new TrackerClient();
        try {
            TrackerServer trackerServer = trackerClient.getConnection();
            // 得到Storage服务器
            StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
            // 创建StorageClient上传文件
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);

            // 得到文件名
            String originalFilename = multipartFile.getOriginalFilename();
            // 得到文件扩展名
            String fileType = VerifyFileType.getFileTypeByHEX(multipartFile.getInputStream());
            if (fileType == null){
                fileType = originalFilename;
            }
            // 上传文件
            return storageClient1.upload_file1(multipartFile.getBytes(), fileType, null);
        } catch (IOException | MyException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 初始化FastDFS链接程序
     */
    private void initFastDFS() {
        try {
            ClientGlobal.initByTrackers(tracker_server);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionCast.cast(FileSystemCode.FS_INITFDFSERROR);
        }
    }
}
